package com.cxq;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by cxq on 2020/7/26.
 */
public class OddEvenPrint2 {

    private int i = 0;
    //非公平锁
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    //奇数打印方法，由奇数线程调用
    public void odd(){
        lock.lock();
        try{
            //判断小于10
            while (i < 10) {
                //打印奇数
                if (i % 2 == 1) {
                    System.out.println(Thread.currentThread().getName()+"：" + i);
                    i++;
                    condition.signal();//唤醒偶数线程打印
                } else {
                    try {
                        condition.await();//等待偶数线程打印
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }finally {
            lock.unlock();
        }
    }
    //偶数打印方法，由偶数线程调用
    public synchronized void even(){
        while(i<10) {
            lock.lock();
            try {
                //打印奇数
                if (i % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                    i++;
                    condition.signal();//唤醒奇数线程打印
                } else {
                    try {
                        condition.await();//等待奇数线程打印
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        final OddEvenPrint2 oddEvenPrint = new OddEvenPrint2();
        //开启奇数线程打印
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                oddEvenPrint.even();
            }
        },"偶数线程");
        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                oddEvenPrint.odd();
            }
        },"奇数线程");
        thread1.start();
        thread2.start();
    }
}
